package com.example.hcd.functionactivity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.hcd.R;
import com.example.hcd.datamanage.UserInfo;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.ToastHelp;
import com.wheel.StrericWheelAdapter;
import com.wheel.WheelView;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnticipateOvershootInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class PersonalInfoActivity extends BaseActivity implements OnClickListener{
	private View main_view;
	private LayoutInflater inflater;
	private UserInfo userInfo;
	
	//选择性别
	private View popview;
	private PopupWindow popipwindow;
	private TextView xiaedit1;
	
	private TextView xiaedit2;
	
	//滚动时间
	private WheelView yearWheel,monthWheel,dayWheel;
	public static String[] yearContent=null;
	public static String[] monthContent=null;
	public static String[] dayContent=null;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mPageName = "PersonalInfoActivity";
		// inflater 是用来找 res/layout 下的 xml 布局文件，并且实例化；
		inflater = LayoutInflater.from(this);
		main_view = inflater.inflate(R.layout.personal_info_view, null);
		setContentView(main_view);
		// 返回键
		ImageView backBtn = (ImageView) findViewById(R.id.title_bar_btn_left);
		// 提交键
		ImageView uploadBtn = (ImageView) findViewById(R.id.title_bar_btn_right);
		backBtn.setOnClickListener(this);
		uploadBtn.setOnClickListener(this);
		initView();
		
	}
	
	private void initView()
	{
		userInfo = UserInfo.getUserInfor();
		
		//初始化时间滚动
		initContent();
		
		
		xiaedit1 = (TextView)main_view.findViewById(R.id.title11);
		xiaedit1.setOnClickListener(this);
		popview = inflater.inflate(R.layout.my_popup_view, null);
		
		LinearLayout addline1 = (LinearLayout) popview.findViewById(R.id.addline);
		for (int i = 0; i < 3; i++) {
			final View item = (View) inflater.inflate(R.layout.my_popup_item, null);
			if (i == 0) {
				TextView texttitle = (TextView) item.findViewById(R.id.menu_text);
				texttitle.setText("请选择性别？？");
				addline1.addView(item);
			} else {
				final TextView text = (TextView) item.findViewById(R.id.menu_text);
				if(i==1)
				{
					text.setText("男");	
				}else
				{
					text.setText("女");
				}
				
				addline1.addView(item);

				text.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						xiaedit1.setText(text.getText().toString());
						popipwindow.dismiss();
					}
				});
				
				TextView cancel = (TextView) popview.findViewById(R.id.cancel_btn);
				cancel.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						popipwindow.dismiss();
					}
				});

			}
		}
		
		popipwindow = new PopupWindow(popview, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		popipwindow.setBackgroundDrawable(new BitmapDrawable());
		xiaedit2 = (TextView)main_view.findViewById(R.id.title21);
		xiaedit2.setOnClickListener(this);
		
		initData();
		
	}
	
	private void initData()
	{
		EditText text = (EditText)main_view.findViewById(R.id.editText);
		text.setText(userInfo.getName());
		
		xiaedit1.setText(userInfo.getGender());
		
		
		
		xiaedit2.setText(userInfo.getBirthday(false));
		
		text = (EditText)main_view.findViewById(R.id.editText3);
		text.setText(userInfo.getOffice_tel());
		
		text = (EditText)main_view.findViewById(R.id.editText4);
		text.setText(userInfo.getOffice_fax());
		
		text = (EditText)main_view.findViewById(R.id.editText5);
		text.setText(userInfo.getMobileNumber());
		
		text = (EditText)main_view.findViewById(R.id.editText6);
		text.setText(userInfo.getEmail());
		
		text = (EditText)main_view.findViewById(R.id.editText7);
		text.setText(userInfo.getQq());
		
		text = (EditText)main_view.findViewById(R.id.editText8);
		text.setText(userInfo.getHome_address());
		
		text = (EditText)main_view.findViewById(R.id.editText9);
		text.setText(userInfo.getZip_code());
		
		text = (EditText)main_view.findViewById(R.id.editText10);
		text.setText(userInfo.getHome_tel());
		
	}
	
	public void initContent()
	{
		yearContent = new String[50];
		for(int i=0;i<50;i++)
			yearContent[i] = String.valueOf(i+1970);
		
		monthContent = new String[12];
		for(int i=0;i<12;i++)
		{
			monthContent[i]= String.valueOf(i+1);
			if(monthContent[i].length()<2)
	        {
				monthContent[i] = "0"+monthContent[i];
	        }
		}
			
		dayContent = new String[31];
		for(int i=0;i<31;i++)
		{
			dayContent[i]=String.valueOf(i+1);
			if(dayContent[i].length()<2)
	        {
				dayContent[i] = "0"+dayContent[i];
	        }
		}	
		
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		int id = arg0.getId();
		
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(main_view.getWindowToken(), 0);
		switch (id) {
		case R.id.title_bar_btn_left:
			finish();
			break;
		case R.id.title_bar_btn_right:
			if(isCanUpload())
			{
				UpdateLoadInfo upload = new UpdateLoadInfo();
				upload.execute();
			}
			break;
		case R.id.title11:
			popipwindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
			popipwindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
			popipwindow.showAsDropDown(arg0);
			// 设置允许在外点击消失
			popipwindow.setOutsideTouchable(true);
			popipwindow.setFocusable(true);
			popipwindow.update();
			break;
			
		case R.id.title21:
		{
			View view = ((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.date_choose_view, null); 
			
    		Calendar calendar = Calendar.getInstance();
    	    int curYear = calendar.get(Calendar.YEAR);
            int curMonth= calendar.get(Calendar.MONTH)+1;
            int curDay = calendar.get(Calendar.DAY_OF_MONTH);
     	    
    	    yearWheel = (WheelView)view.findViewById(R.id.yearwheel);
    	    monthWheel = (WheelView)view.findViewById(R.id.monthwheel);
    	    dayWheel = (WheelView)view.findViewById(R.id.daywheel);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);  
            builder.setView(view); 
            
            yearWheel.setAdapter(new StrericWheelAdapter(yearContent));
		 	yearWheel.setCurrentItem(curYear-2013);
		    yearWheel.setCyclic(true);
		    yearWheel.setInterpolator(new AnticipateOvershootInterpolator());
	        
	 
	        monthWheel.setAdapter(new StrericWheelAdapter(monthContent));
	       
	        monthWheel.setCurrentItem(curMonth-1);
	     
	        monthWheel.setCyclic(true);
	        monthWheel.setInterpolator(new AnticipateOvershootInterpolator());
	        
	        dayWheel.setAdapter(new StrericWheelAdapter(dayContent));
	        dayWheel.setCurrentItem(curDay-1);
	        dayWheel.setCyclic(true);
	        dayWheel.setInterpolator(new AnticipateOvershootInterpolator());

	        builder.setTitle("选取时间");  
	        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {  

	        	@Override  
            	public void onClick(DialogInterface dialog, int which) {  
            	
	        		StringBuffer sb = new StringBuffer();  
	        		sb.append(yearWheel.getCurrentItemValue()).append("-")
	        		.append(monthWheel.getCurrentItemValue()).append("-")
	        		.append(dayWheel.getCurrentItemValue());
	        		xiaedit2.setText(sb);
	        		dialog.cancel();
            	}  
	        });  
       
	        builder.show();
			
		}
			break;

		default:
			break;
		}
	}
	
	/*
	 * 传送数据到服务器
	 */
	private class UpdateLoadInfo extends AsyncTask<String, Integer, String> {
		// private ProgressDialog mProgress;
		public UpdateLoadInfo() {

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try {
				
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				
				vs.add(new BasicNameValuePair("username",userInfo.getUsername()));
				EditText text = (EditText)main_view.findViewById(R.id.editText);
				
				vs.add(new BasicNameValuePair("name",text.getText().toString()));
				
				vs.add(new BasicNameValuePair("gender",xiaedit1.getText().toString().equals("男")?"1":"2"));
				
				if(xiaedit2.getText().toString().contains("-"))
				{
					vs.add(new BasicNameValuePair("birthday",xiaedit2.getText().toString()));
				}
				
				text = (EditText)main_view.findViewById(R.id.editText3);
				
				if(text.getText().toString()!=null)
				{
					vs.add(new BasicNameValuePair("office_tel",text.getText().toString()));
				}
				
				
	
				text = (EditText)main_view.findViewById(R.id.editText4);
				
				if(text.getText().toString()!=null)
				{
				vs.add(new BasicNameValuePair("office_fax",text.getText().toString()));
				}
				text = (EditText)main_view.findViewById(R.id.editText5);
				vs.add(new BasicNameValuePair("mobileNumber",text.getText().toString()));
		
				text = (EditText)main_view.findViewById(R.id.editText6);
				if(text.getText().toString()!=null)
				{
				vs.add(new BasicNameValuePair("email",text.getText().toString()));
				}
				text = (EditText)main_view.findViewById(R.id.editText7);
				if(text.getText().toString()!=null)
				{
				vs.add(new BasicNameValuePair("qq",text.getText().toString()));
				}
				text = (EditText)main_view.findViewById(R.id.editText8);
				if(text.getText().toString()!=null)
				{
				vs.add(new BasicNameValuePair("home_address",text.getText().toString()));
				}
				text = (EditText)main_view.findViewById(R.id.editText9);
				if(text.getText().toString()!=null)
				{
				vs.add(new BasicNameValuePair("zip_code",text.getText().toString()));
				}
				text = (EditText)main_view.findViewById(R.id.editText10);
				if(text.getText().toString()!=null)
				{
				vs.add(new BasicNameValuePair("home_tel",text.getText().toString()));
				}
				response = LinkHelp.post(URLS.getUpdateUserInfo(), vs, false);

				if (response != null) {
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						reader.close();
						result = sb.toString();
						
						System.out.println(result);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			
			if(result!=null)
			{
				JSONObject jsonObject;
	            try {
	                jsonObject = new JSONObject(result);
	                if (jsonObject.isNull("code")) {
	                    String status = jsonObject.getString("status");
	                    UserInfo info = UserInfo.getUserInfor();
	                    if (status.equals("success")) {
	                        Toast.makeText(PersonalInfoActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
	                        userInfo.updateUserInfo();
	                        	finish();
	                    } else {
	                    	String msg = jsonObject.getString("msg");
	                    	ToastHelp.doToastInTop(PersonalInfoActivity.this, msg);
	                    }
	                    
	                }}  
	            catch (JSONException e) {
	                e.printStackTrace();
	            }
			}else
			{
				ToastHelp.doToastInTop(PersonalInfoActivity.this, "网络异常");
			}
			
			
		}

	}
	
	public boolean isCanUpload()  {
		EditText edit = (EditText)main_view.findViewById(R.id.editText);
		if (edit.getText().toString().equals("")) {
			//Toast.makeText(this, "姓名不能为空", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(PersonalInfoActivity.this, "姓名不能为空");
			return false;
		}
		
		edit = (EditText)main_view.findViewById(R.id.editText5);
		if (edit.getText().toString().equals("")) {
			//Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(PersonalInfoActivity.this, "手机号不能为空");
			return false;
		}

		return true;
	}

}
